<template>
  <el-card class="box-card">
  <div slot="header" class="clearfix">
    <span>用户资料</span>
  </div>
  <!-- 内容取 -->
  <el-form label-width="85px" :model="UserInfo" :rules="rule" ref="form">
    <el-form-item label="登录账号:">
      <el-input v-model="UserInfo.username" disabled></el-input>
    </el-form-item>
    <el-form-item label="用户昵称:" prop="nickname">
      <el-input v-model="UserInfo.nickname"></el-input>
    </el-form-item>
    <el-form-item label="用户邮箱:" prop="email">
      <el-input v-model="UserInfo.email"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="updateUser">确认修改</el-button>
      <el-button @click="resetForm">不改了</el-button>
    </el-form-item>
  </el-form>
</el-card>
</template>

<script>
import { updateUserAPI } from '@/api/user'
export default {
  data() {
    return {
      // UserInfo: {
      //   username: this.$store.state.user.user.username,
      //   nickname: this.$store.state.user.user.nickname,
      //   email: this.$store.state.user.user.email
      // }
      UserInfo: { ...this.$store.state.user.user },
      rule: {
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  methods: {
    updateUser() {
      // 完整的验证，验证通过，则调用API方法
      this.$refs.form.validate(async valid => {
        if (!valid) return
        // console.log('验证通过，提交数据')
        const { data: res } = await updateUserAPI(this.UserInfo)
        if (res.code === 0) {
          this.$message.success(res.message)
          // 更新成功，更新vuex中的 user 数据
          this.$store.dispatch('user/getUser')
        } else {
          this.$message.error(res.message)
        }
      })
    },
    resetForm() {
      // resetFields 恢复表单为最初的样子；去掉红色的表单验证提示
      this.$refs.form.resetFields()
      // 将vuex中的数据，更新到组件中
      this.userInfo = { ...this.$store.state.user.user }
    }
  }
}
</script>

<style lang="less" copend>
  .el-card{
    // width: 500px;
    font-size: 14px;
    font-weight: 700;
  }
  .el-form{
    width: 500px;
  }
</style>
